//
//  PlayBar.m
//  ImGuider
//
//  Created by 王鹏宇 on 2017/6/2.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "PlayBar.h"
#import "MyPlayProgressView.h"

@interface PlayBar()<IGAvPlayerManagerDelegate,MyPlayProgressViewDelegate>

@property (nonatomic, strong)IGAvPlayerManager * manager;
@property (nonatomic, strong)MyPlayProgressView * progressBar;
@property (nonatomic, strong)UILabel * currentTimeLabel;
@property (nonatomic, strong)UILabel * totalTimeLabel;
@property (nonatomic, strong)UIButton * playBtn;
@property (nonatomic, strong)UILabel * downloadProgressLabel;
@property (nonatomic, strong)UILabel * currentScenicPointLabel;


@property (nonatomic, strong)UIButton * nextBtn;

@property (nonatomic, strong)UIButton * PreviousBtn;

@property (nonatomic, strong)NSString * playPath;

@end
@implementation PlayBar

+ (instancetype)shareManeger {
    
    return [[self alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 60, SCREEN_WIDTH, 60)];
    
//    static PlayBar *manager;
//
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        manager = [[self alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 60, SCREEN_WIDTH, 60)];
//
//    });
//    return manager;
}

- (void)awakeFromNib {
    
    [super awakeFromNib];
    
    _manager = [IGAvPlayerManager shareManeger];
    _manager.delegate = self;
    self.backgroundColor = [UIColor whiteColor];
    [self createPlayView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(PlayBarchangePlayStateWith:) name:kIGAvPlayerManagerState object:nil];
}


- (void)setProgressValue:(CGFloat)progressValue {
    
    self.progressBar.value = progressValue;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        _manager = [IGAvPlayerManager shareManeger];
        _manager.delegate = self;
        self.backgroundColor = [UIColor whiteColor];
        [self createPlayView];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(PlayBarchangePlayStateWith:) name:kIGAvPlayerManagerState object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(previousBtnClicked) name:@"remotePre" object:nil];
       
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(nextBtnClicked) name:@"remoteNext" object:nil];
    }
    return self;
}

//- (void)stop {
//    
//    [self.manager stop];
//}


- (void)playMusicWithPlayPath:(ScenicPoint *)scenicPoint withIsPlay:(BOOL)isImmediately
{
    self.playPath = scenicPoint.playpath;
    [self.manager playMusic:scenicPoint withIsPlay:isImmediately];
    [self.progressBar setValue:0];
}

- (void)setDownloadProgress:(CGFloat)downloadProgress {
    _downloadProgress = downloadProgress;
    _downloadProgressLabel.text = [NSString stringWithFormat:@"%.f%%",downloadProgress * 100];
    if (_downloadState == DownloadStateDownloading) {
        [self.downloadBtn setProgress:downloadProgress];
    }
}


- (void)setDownloadState:(DownloadState)downloadState {
    _downloadState = downloadState;
    
    switch (downloadState) {
        case DownloadStateDownloading:
        {
            [self.downloadBtn setImage:[UIImage imageNamed:@"continue"] forState:UIControlStateNormal];
            self.downloadProgressLabel.text = @"";
            self.downloadProgressLabel.hidden = NO;
        }
            break;
        case DownloadStateCompleted:
        {
            [self.downloadBtn setImage:[UIImage imageNamed:@"complete"] forState:UIControlStateNormal];
            self.downloadProgressLabel.text = @"";
            self.downloadProgressLabel.hidden = YES;
            self.downloadBtn.userInteractionEnabled = NO;
            [self.downloadBtn setProgress:0.f];
        }
            break;
        case DownloadStateFailed:
        {
            [self.downloadBtn setImage:[UIImage imageNamed:@"retry"] forState:UIControlStateNormal];
            [self.downloadBtn setProgress:0.f];
            self.downloadProgressLabel.hidden = YES;
        }
            break;
        default:{
            [self.downloadBtn setImage:[UIImage imageNamed:@"download"] forState:UIControlStateNormal];
            [self.downloadBtn setProgress:0.f];
             self.downloadProgressLabel.text = @"";
             self.downloadProgressLabel.hidden = YES;
        }
            break;
    }
}

- (void)downloadBtnClicked:(UIButton *)btn {
    
    btn.userInteractionEnabled = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.688 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        btn.userInteractionEnabled = YES;
    });
    switch (_downloadState) {
        case DownloadStateDownloading:
        {
            if (_delegate && [_delegate respondsToSelector:@selector(downloadSuspend)]) {
                [_delegate downloadSuspend];
                _downloadState = DownloadStateSuspened;
                [_downloadBtn setProgress:0.f];
                [self setDownloadState:DownloadStateNone];
            }
        }
            break;
            
        default:
        {
            
            
            if (![AppManager sharedManager].allowWhenDownload && [AppManager sharedManager].networkState == AFNetworkReachabilityStatusReachableViaWWAN) {
                
                [IGAlertView alertWithTitle:@"" message:MYLocalizedString(@"PUBLIC_NOWIFI_DOWNLOAD_ALERT_CONTENT", nil) cancelButtonTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) commitBtn:MYLocalizedString(@"PUBLIC_NOWIFI_DOWNLOAD_ALERT_ALLOW", nil) commit:^{
                    
                    [AppManager sharedManager].allowWhenDownload = YES;
                    
                    if (_delegate && [_delegate respondsToSelector:@selector(downloadStart)]) {
                        [_delegate downloadStart];
                    }
                    
                } cancel:nil];
                return;
            }
            
            if (_delegate && [_delegate respondsToSelector:@selector(downloadStart)]) {
                [_delegate downloadStart];
            }

        }
            break;
    }
}

- (void)createPlayView {
    
    _PreviousBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_PreviousBtn addTarget:self action:@selector(previousBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    _PreviousBtn.frame = CGRectMake(12, 12.5, 35, 35);
    
    [_PreviousBtn setImage:[UIImage imageNamed:@"lines_before"] forState:UIControlStateNormal];
    [self addSubview:_PreviousBtn];
    
    
    _downloadBtn = [[ProgressBtn alloc] init];
    _downloadBtn.frame = CGRectMake(self.frame.size.width - 47, 12.5, 35, 35);
    _downloadBtn.space = 2.f;
    _downloadBtn.progressColor = kThemeColor;
    [_downloadBtn setImage:[UIImage imageNamed:@"download"] forState:UIControlStateNormal];
    [_downloadBtn addTarget:self action:@selector(downloadBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_downloadBtn];
    
    _downloadProgressLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.frame.size.width - 47, 47.5, 35, 12)];
    _downloadProgressLabel.textColor = kThemeColor;
    _downloadProgressLabel.font = Font(10);
    _downloadProgressLabel.textAlignment = NSTextAlignmentCenter;
    [self addSubview:_downloadProgressLabel];
    _nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_nextBtn addTarget:self action:@selector(nextBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    _nextBtn.frame = CGRectMake(self.frame.size.width - 86, 12.5, 35, 35);
    [_nextBtn setImage:[UIImage imageNamed:@"lines_next"] forState:UIControlStateNormal];
    [self addSubview:_nextBtn];
    
    
    _progressBar = [[MyPlayProgressView alloc] initWithFrame:CGRectMake(50, 28.5, self.frame.size.width - 162, 3)];
    _progressBar.delegate = self;
    _progressBar.playProgressBackgoundColor = kThemeColor;
    _progressBar.trackBackgoundColor = [UIColor lightGrayColor];
    
    [self addSubview:_progressBar];
    
    CGFloat X = CGRectGetMaxX(self.progressBar.frame);
    
    
    _totalTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(X , 22.5, 27, 15)];
    _totalTimeLabel.textAlignment = NSTextAlignmentLeft;
    _totalTimeLabel.text = @"";
        [self addSubview:_totalTimeLabel];
    _totalTimeLabel.font = Font(9);
    _totalTimeLabel.textColor = kContentColor;
    
    
    //    _currentTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(72, 33, 25, 15)];
    //    _currentTimeLabel.text = @"00:00";
    //    _currentTimeLabel.font = Font(8);
    //    _currentTimeLabel.textColor = kContentColor;
    //        [self addSubview:_currentTimeLabel];

    
}


- (void)previousBtnClicked {
    
    if (![self.manager.currentURL isEqualToString:self.playPath]) {
        return;
    }
    
    if (_delegate && [_delegate respondsToSelector:@selector(changeRecordPointWith:isAutomatic:)]) {
        self.PreviousBtn.userInteractionEnabled = NO;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.PreviousBtn.userInteractionEnabled = YES;
        });
        [_delegate changeRecordPointWith:-1 isAutomatic:NO];
        
        
        if (self.type == 1) {
            [MobClick event:@"4_0_7"];
        } else if (self.type == 2) {
            [MobClick event:@"7_0_9"];
        }
        
    }
}

- (void)nextBtnClicked {
    
    if (_delegate && [_delegate respondsToSelector:@selector(changeRecordPointWith:isAutomatic:)]) {
        self.nextBtn.userInteractionEnabled = NO;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.nextBtn.userInteractionEnabled = YES;
        });
        [_delegate changeRecordPointWith:1 isAutomatic:NO];
        
        if (self.type == 1) {
            [MobClick event:@"4_0_8"];
        } else if (self.type == 2) {
            [MobClick event:@"7_0_10"];
        }
    }
}


#pragma mark - JSDownloadAnimationDelegate

//- (void)animationStart {
//    
//    if (_delegate && [_delegate respondsToSelector:@selector(downloadStart)]) {
//        [self.delegate downloadStart];
//    }
//}
//
//- (void)animationSuspend {
//    
//    if (_delegate && [_delegate respondsToSelector:@selector(downloadSuspend)]) {
//        [self.delegate downloadSuspend];
//    }
//}

#pragma mark - progressDelegate

-  (void)beiginSliderScrubbing {
    
   
}

- (void)endSliderScrubbing {
    
    [self.manager musicSeekToTime:self.progressBar.value];
    
}

- (void)sliderScrubbing {
    
    self.totalTimeLabel.text = [_manager timeFormatted:_manager.totaltime - self.progressBar.value * _manager.totaltime];
    
    IGLog(@"----%f",self.progressBar.value);
}

- (void)playOrPause {
    
    if ([IGAvPlayerManager shareManeger].isPlay) {
        [self.manager pause];
        
        if (self.type == 1) {
            [MobClick event:@"4_0_6"];
        } else if (self.type == 2) {
            [MobClick event:@"7_0_2"];
        }

    }else {
        [self.manager play];
        
        if (self.type == 1) {
            [MobClick event:@"4_0_5"];
        } else if (self.type == 2) {
            [MobClick event:@"7_0_1"];
        }
    }
}

#pragma mark - avPlayerDelegate

- (void)PlayBarchangePlayStateWith:(NSNotification *)notif
{
    NSInteger state = [notif.userInfo[kIGAvPlayerManagerState] integerValue];
    
    NSString  * url = notif.userInfo[kCurrentPlayURL];
    if (![url isEqualToString:self.playPath]) {
        return;
    }
    switch (state) {
        case AVPlayerPlayStatePreparing:
        case AVPlayerPlayStateBeigin:{
            
            [self.progressBar.sliderBtn setImage:[UIImage imageNamed:@"lines_pause"] forState:UIControlStateNormal];
            //[_sliderBtn setImage:[UIImage imageNamed:@"lines_pause"] forState:UIControlStateSelected];
            // self.totalTimeLabel.text = self.manager.durantion;
        }
            break;
        case AVPlayerPlayStatePlaying:
        {
            [self.progressBar.sliderBtn setImage:[UIImage imageNamed:@"lines_pause"] forState:UIControlStateNormal];
            
        }
            break;
        case AVPlayerPlayStatePause: {
            [self.progressBar.sliderBtn setImage:[UIImage imageNamed:@"lines_play"] forState:UIControlStateNormal];
            
        }
            break;
        case AVPlayerPlayStateEnd:
        {
            self.totalTimeLabel.text = @"00:00";
            [self.progressBar.sliderBtn setImage:[UIImage imageNamed:@"lines_play"] forState:UIControlStateNormal];
        }
            break;
        case AVPlayerPlayStateNotPlay:
    
        {
            self.totalTimeLabel.text = @"";
            self.currentTimeLabel.text = @"";
            self.progressBar.value = 0.;
            [self.progressBar.sliderBtn setImage:[UIImage imageNamed:@"lines_play"] forState:UIControlStateNormal];
        }
            break;
        case AVPlayerPlayStateseekToZeroBeforePlay:
        {
            self.progressBar.value = 0.;
            
        }
            break;
            
        default:
            break;
    }
    
}

- (void)sequentialPlay {
    
    if (_delegate &&[_delegate respondsToSelector:@selector(changeRecordPointWith:isAutomatic:)]) {
        [_delegate changeRecordPointWith:1 isAutomatic:YES];
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)updateBufferProgress:(NSTimeInterval)progress {
    
    self.progressBar.trackValue = progress;
   
}
- (void)updateProgressWith:(CGFloat)value {
   
    if (![[IGAvPlayerManager shareManeger].currentURL isEqualToString:self.playPath]) {
        return;
    }
    [self.progressBar setValue:value];
    
    self.totalTimeLabel.text = self.manager.durantion;
    IGLog(@"^^^^^^^^^^^^%f",value/self.manager.totaltime);
}


- (void)showBigView:(UIButton *)button {
    if (!button.selected) {
        self.frame = CGRectMake(0, SCREEN_HEIGHT/3, SCREEN_WIDTH, SCREEN_HEIGHT/3*2);
        button.selected = YES;
        
        
    }else {
        
        self.frame = CGRectMake(0, SCREEN_HEIGHT - 120, SCREEN_WIDTH, 120);
        button.selected = NO;
        
    }
}






//- (void)sliderChange:(UISlider *)slider {
//
//    CGFloat value = slider.value *20;
//
//    [_manager musicSeekToTime:value];
//
//    IGLog(@"%f",value);
//
//}
/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
